/**
 * 在一个由 '0' 和 '1' 组成的二维矩阵内，找到只包含 '1' 的最大正方形，并返回其面积。
 */
public class Test221 {

    public static void main(String[] args) {
        char[][] square = {{'1','0','1','0','0'},{'1','0','1','1','1'},{'1','1','1','1','1'},{'1','0','0','1','0'}};
        System.out.println(maximalSquare(square));
    }

    public static int maximalSquare(char[][] matrix) {

        int[][] max_len = new int[matrix.length][matrix[0].length];
        int max_size = matrix[0][0]-48;

        for (int i = 0; i < matrix.length; i++) {
            max_len[i][0] = matrix[i][0]-48;
            max_size = Math.max(max_size,max_len[i][0]);
        }
        for (int i = 0; i < matrix[0].length; i++) {
            max_len[0][i] = matrix[0][i]-48;
            max_size = Math.max(max_size,max_len[0][i]);
        }

        for (int i = 1; i < matrix.length; i++) {
            for (int j = 1; j < matrix[0].length; j++) {
                if (matrix[i][j] == '1'){
                    max_len[i][j] = Math.min(Math.min(max_len[i][j-1],max_len[i-1][j-1]),max_len[i-1][j])+1;
                    max_size = Math.max(max_size,max_len[i][j]);
                }
            }
        }

        return max_size*max_size;
    }
}
